package com.tian.view.draw.shader

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RadialGradient
import android.graphics.Shader
import android.util.AttributeSet
import com.tian.util.view.DisplayUtil
import com.tian.view.common.BaseClickView

/**
 * @author tiansongtao
 * @date 2023/1/5 18:01
 *
 * 放射性渐变
 */
class RadialGradientView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
        BaseClickView(context, attrs, defStyleAttr) {

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null)

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
    }

    private val paint = Paint()
    private val textPaint = Paint().apply {
        color = Color.BLACK
        style = Paint.Style.FILL_AND_STROKE
        textSize = DisplayUtil.spToPx(18f)
        isAntiAlias = true
        isFakeBoldText = true
        textAlign = Paint.Align.CENTER
    }

    private val gradient1: RadialGradient by lazy {
        /**
         * 构造函数1： 两色渐变
         * centerX\centerY: 渐变色圆中心点坐标
         * radius: 渐变色半径
         * centerColor: 起始点(中心点)颜色 edgeColor 终止点(边缘)颜色， 颜色值必须带有alpha
         * tileMode 填充模式
         */
        RadialGradient(/* centerX = */ width / 2f, /* centerY = */ height / 2f, /* radius = */ width / 2f,
                /* centerColor = */ 0xFFFF0000.toInt(), /* edgeColor = */ 0xFF00FF00.toInt(), /* tileMode = */
                Shader.TileMode.REPEAT)
    }

    private val gradient2: RadialGradient by lazy {
        val colors = intArrayOf(
                0xFFFF0000.toInt(), 0xFF00FF00.toInt(),
                0xFF0000FF.toInt(), 0xFF00FFFF.toInt(), 0xFFFF0000.toInt(),
        )
        val positions = floatArrayOf(0f, 0.2f, 0.4f, 0.6f, 1f)
        /**
         * 构造函数2: 多色渐变
         * centerX\centerY: 渐变色圆中心点坐标
         * radius: 渐变色半径
         * colors与positions 一一对应，positions取值0~1，表示
         *  每个相对应的颜色在渐变色中的百分比位置。
         *  eg：color[0]确定颜色，positions[0]=0.2f表示这个颜色在整条渐变色的20%处
         * tileMode 填充模式
         */
        RadialGradient(/* centerX = */ width / 2f, /* centerY = */ height / 2f, /* radius = */
                width / 2f, /* colors = */ colors, /* stops = */ positions, /* tileMode = */ Shader.TileMode.MIRROR)
    }

    private var change = true

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.shader = if (change) gradient1 else gradient2
        canvas.drawCircle(width / 2f, height / 2f, width / 2f, paint)
    }

    override fun singleClick() {
        super.singleClick()
        change = !change
        postInvalidate()
    }
}